<template>
  <div>
    <Row :gutter="10">
      <Col>
        <Card>
          <div class="live_wrapper clearfix" style="margin-top: 10px">
            <Select v-model="filter.shop_id"
                    style="width: 200px;margin-right: 10px;float: left;"
                    filterable
                    label-in-value
                    @on-change="search"
                    placeholder="请选择门店">
              <Option :value="0">全部</Option>
              <Option :value="item.id" v-for="(item, index) in shop_list" :key="index">{{ item.name }}</Option>
            </Select>
          </div>

          <!--    平台/门店订单统计      -->
          <div class="flow statistics">
            <div class="item">
              <div class="flex-row" style="margin-bottom: 10px">
                <div class="color-33 font-18" style="margin-right: 20px">总收入 (元)</div>
                <Tooltip content="门店已付款的订单总额" max-width="200">
                  <Icon type="md-alert" color="#d3dae5" style="cursor: pointer;" size="19" />
                </Tooltip>
              </div>
              <div class="color-33 font-18">{{ statisticsInfo.money_order_all }}</div>
            </div>
            <div class="item">
              <div class="flex-row" style="margin-bottom: 10px">
                <div class="color-33 font-18" style="margin-right: 20px">待结算金额 (元)</div>
                <Tooltip content="门店还未服务完成的订单总额" max-width="200">
                  <Icon type="md-alert" color="#d3dae5" style="cursor: pointer;" size="19" />
                </Tooltip>
              </div>
              <div class="color-33 font-18">{{ statisticsInfo.money_order_djs }}</div>
            </div>
            <div class="item">
              <div class="flex-row" style="margin-bottom: 10px">
                <div class="color-33 font-18" style="margin-right: 20px">冻结金额 (元)</div>
                <Tooltip content="发起提现，平台正在审核中，该部分资金暂无法使用" max-width="200">
                  <Icon type="md-alert" color="#d3dae5" style="cursor: pointer;" size="19" />
                </Tooltip>
              </div>
              <div class="color-33 font-18">{{ statisticsInfo.money_order_cashing }}</div>
            </div>
            <div class="item">
              <div class="flex-row" style="margin-bottom: 10px">
                <div class="color-33 font-18" style="margin-right: 20px">可提现金额 (元)</div>
                <Tooltip content="每笔订单产生后，微信官方会自动收取0.54%的手续费，平台不加收任何手续费" max-width="200">
                  <Icon type="md-alert" color="#d3dae5" style="cursor: pointer;" size="19" />
                </Tooltip>
              </div>
              <div class="color-33 font-18">{{ statisticsInfo.money_order_ky }}</div>
              <div class="flex-row center-x font-14" style="justify-content: space-between">
                <div style="color: #07BD21;padding: 10px;cursor: pointer;"
                     @click="doCash"
                     v-if="permissionList.indexOf('assets-cash') !== -1 && !!filter.shop_id && statisticsInfo.money_order_ky > 0">
                  去提现
                </div>
                <div style="color: #2b76ee;padding: 10px;cursor: pointer;"
                     @click="cashOutRecord"
                     v-if="permissionList.indexOf('cash-record') !== -1">提现记录
                </div>
              </div>
            </div>
          </div>

          <!--     平台/门店账单明细     -->
          <div class="flex-row center-x" style="justify-content: space-between;margin-top: 20px;">
            <p class="admin_title">账单明细</p>
            <div class="flex-row center-x">
              <Input v-model="filter.name"
                     @on-search="search"
                     search
                     enter-button="搜索"
                     placeholder="请输入客户姓名"
                     style="display:inline-table; width: 210px; margin-right: 10px" />
              <Input v-model="filter.phone"
                     @on-search="search"
                     search
                     enter-button="搜索"
                     placeholder="请输入手机号码"
                     style="display:inline-table; width: 210px; margin-right: 10px" />
              <DatePicker type="daterange"
                          v-model="filter.created_at"
                          @on-change="search"
                          placement="bottom-end"
                          placeholder="选择时间区间"
                          style="width: 200px; margin-right: 10px;"></DatePicker>
              <Button type="primary"
                      @click.stop="exportData()"
                      style="width: 90px;height: 32px;font-size: 14px; float: right; margin-left: 10px">导出
              </Button>
            </div>
          </div>
          <Row class="margin-top-10 table_pattern table_pattern2">
            <Table style="width: calc(100vw - 256px - 36px - 32px)"
                   :loading="loading"
                   :columns="columns"
                   :data="list"></Table>
          </Row>
          <Row class="margin-top-10">
            <Page :total="pagenation.totalPage"
                  :page-size="pagenation.perPage"
                  :current="pagenation.currentPage"
                  show-elevator
                  show-total
                  @on-change="change"></Page>
          </Row>
        </Card>
      </Col>
    </Row>

    <Modal v-model="showCashoutModal"
           title="提现"
           :width="this.current_step == 1 ? '825px' : '800px'"
           :mask-closable="false"
           class="public_modal_header edit_modal">
      <div class="cash_out_modal">
        <template>
          <Steps :current="current_step" style="margin-top: 20px;">
            <Step title="请输入本次提现资料"></Step>
            <Step title="下载结算函" content="打印签字和盖章"></Step>
            <Step title="上传结算函" content="提现金额将在3个工作日内到账"></Step>
          </Steps>
        </template>

        <div v-show="current_step == 0">
          <div class="title">银行账户相关信息</div>
          <div class="item">
            <div class="item-name required">账户名称</div>
            <Input v-model="formValidate.bank_account" placeholder="请输入账户名称" :maxlength="40" class="item-content" />
          </div>
          <div class="item">
            <div class="item-name required">银行账号</div>
            <Input v-model="formValidate.account" placeholder="请输入银行账号" :maxlength="40" class="item-content" />
          </div>
          <div class="item">
            <div class="item-name required">开户行所在地</div>
            <Input v-model="formValidate.bank_address" placeholder="请输入开户行所在地" :maxlength="40" class="item-content" />
          </div>
          <div class="item">
            <div class="item-name required">开户行</div>
            <Input v-model="formValidate.bank" placeholder="请输入开户行" :maxlength="20" class="item-content" />
          </div>

          <div class="title">申请人相关信息</div>
          <div class="item">
            <div class="item-name required">申请人姓名</div>
            <Input v-model="formValidate.name" placeholder="请输入申请人姓名" :maxlength="40" class="item-content" />
          </div>
          <div class="item">
            <div class="item-name required">手机号码</div>
            <Input v-model="formValidate.phone" placeholder="请输入手机号码" :maxlength="11" class="item-content" />
          </div>
          <div class="item">
            <div class="item-name">备注</div>
            <Input v-model="formValidate.remark" placeholder="请输入备注" type="textarea" />
          </div>

          <div class="btns">
            <Button type="primary" @click="stepOne">下一步</Button>
          </div>
        </div>

        <div v-show="current_step == 1">
          <div class="title-img">提现结算函(下为示例图)</div>
          <div class="download-wrap">
            <div class="download-pic"
                 @click="handleView('https://img.cyjxy.com/FuZfzoVddSti_5Dxr5-MPnpSCh4f.png')">
              <img src="https://img.cyjxy.com/FuZfzoVddSti_5Dxr5-MPnpSCh4f.png"
                   alt=""
                   style="cursor: pointer" />
            </div>
            <div class="download-tip">
              <p>注意：</p>
              <p>1.点击【下载】，下载结算函至本地。</p>
              <p>2.核对数据无误后，打印、签字并加盖公章。</p>
              <p>3.拍照并上传结算函。</p>
              <Button type="primary"
                      style="margin-top: 10px; width: 100px"
                      @click="download">下载
              </Button>
            </div>
          </div>
          <div class="btns">
            <Button type="primary" @click="prev" style="margin-right: 10px;">上一步</Button>
            <Button type="primary" @click="next">下一步</Button>
          </div>
        </div>

        <div v-show="current_step == 2" style="margin: 0 100px">
          <div class="title">上传结算函</div>
          <div class="item" style="align-items: unset;height: fit-content">
            <div class="item-name required">结算函</div>
            <div class="clearfix live_cover">
              <div style="float: left;margin-right: 18px;">
                <template>
                  <div class="demo-upload-list" v-if="formValidate.receipt_js">
                    <img :src="formValidate.receipt_js" style='width:150px; height:120px;object-fit: cover;'>
                    <div class="demo-upload-list-cover">
                      <Icon type="ios-eye-outline" @click.native="handleView(formValidate.receipt_js)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="handleRemove()"></Icon>
                    </div>
                  </div>
                  <div v-if="!formValidate.receipt_js">
                    <div class="no_pic"><img src="../../assets/images/expo/pic2.png" alt="" width="24" /></div>
                  </div>
                </template>
              </div>
              <Upload ref="upload"
                      :max-size="1024"
                      :show-upload-list="false"
                      action="https://up.qiniup.com"
                      :on-format-error="handleFormatError"
                      :on-progress="handleProgress"
                      :on-success="handleSuccess"
                      :on-error="handleError"
                      :format="['jpg', 'png', 'jpeg']"
                      :data="{token:upload_token}"
                      :before-upload="handleBeforeUpload"
                      style="float: left;">
                <Button
                    style="width:80px;height:30px;background:rgba(248,249,250,1);border:1px solid rgba(232,233,237,1);border-radius:2px;">
                  上传文件
                </Button>
              </Upload>
            </div>
          </div>
          <div class="btns">
            <Button type="primary" @click="prev" style="margin-right: 10px;">上一步</Button>
            <Button :loading="isSubmitting" type="primary" @click="handleSubmit">提现</Button>
          </div>
        </div>
      </div>


    </Modal>

    <Modal title="查看图片" v-model="visible">
      <img :src="imgName" v-if="visible" style="width: 100%">
    </Modal>
  </div>
</template>
<script>

import {
  getQiniu,
  childBtnPermission,
  shopForSelect,
  orderStatistics,
  orderRecordList,
  addCash,
  latestCashInfo,
  getJsTemp,
} from '@/api/main'
import Time from "@/tool/Time";

export default {
  name: 'assets',
  data () {
    return {
      permissionList: [],
      pagenation: {},
      columns: [
        {
          key: 'name',
          title: '客户姓名',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.name)
          },
        },
        {
          key: 'phone',
          title: '手机号码',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.phone)
          },
        },
        {
          key: 'shop_name',
          title: '门店',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.shop_name)
          },
        },
        {
          key: 'good_name',
          title: '商品',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.good_name)
          },
        },
        {
          key: 'money',
          title: '收入(元)',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.money)
          },
        },
        {
          key: 'order_sn',
          title: '订单号',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.order_sn)
          },
        },
        {
          key: 'moneys',
          title: '入账/支出(元)',
          align: 'center',
          render: (h, params) => {
            if (params.row.order_type == 1) {
              return h('strong', { style: { color: '#FD8383' } }, params.row.moneys)
            } else {
              return h('strong', { style: { color: '#5B5B5B' } }, params.row.moneys)
            }
          },
        },
        {
          key: 'created_time',
          title: '创建时间',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.created_time || '/')
          },
        }
      ],
      list: [],
      loading: true,
      filter: {
        page: 0,
        page_size: 20,
        shop_id: 0,
        name: '',
        phone: '',
        date_range: '',
        created_at: ['', ''],
      },
      shop_list: [],
      statisticsInfo: {
        money_order_all: 0,
        money_order_djs: 0,
        money_order_cashing: 0,
        money_order_ky: 0
      },
      formValidate: {
        shop_id: 0,
        bank_account: '',
        account: '',
        bank_address: '',
        bank: '',
        name: '',
        phone: '',
        money_origin: 0.01,
        money_wx: 0,
        money: 0,
        receipt_js: '',
        remark: '',
      },
      showCashoutModal: false,
      isSubmitting: false,
      current_step: 0,
      visible: false,
      imgName: '',
      upload_token: '',
    }
  },
  watch: {
    "filter.shop_id": function () {
      this.getStatistics()
    },
    'filter.created_at': function () {
      let created_at_start = Time.dateToTimestamp(this.filter.created_at[0])
      let created_at_end = Time.dateToTimestamp(this.filter.created_at[1])
      if (created_at_start !== 0 && created_at_end !== 0) {
        this.filter.date_range = created_at_start + '-' + created_at_end
      } else {
        this.filter.date_range = ''
      }
    },
  },
  methods: {
    download () {
      getJsTemp(this.formValidate).then(res => {
        if (res.code == 0) {
          var downloadFileUrl = res.file
          var elemIF = document.createElement("iframe");
          elemIF.src = downloadFileUrl;
          elemIF.style.display = "none";
          document.body.appendChild(elemIF);
        }
      })
    },
    stepOne () {
      if (this.formValidate.bank_account == '') {
        this.$Message.error("请输入账户名称");
        return;
      }
      if (this.formValidate.account == '') {
        this.$Message.error("请输入银行账号");
        return;
      }
      if (this.formValidate.bank_address == '') {
        this.$Message.error("请输入开户行地址");
        return;
      }
      if (this.formValidate.bank == '') {
        this.$Message.error("请输入开户行");
        return;
      }
      if (this.formValidate.name == '') {
        this.$Message.error("请输入申请人姓名");
        return;
      }
      if (this.isPhoneIncorrect(this.formValidate.phone)) {
        this.$Message.error("请输入正确手机号码");
        return;
      }
      this.current_step += 1;
    },
    prev () {
      this.current_step -= 1;
    },
    next () {
      this.current_step += 1;
    },
    handleBeforeUpload (file) {
      if (file.size > 1024 * 1024) {
        this.$Message.error("图片不超过1M")
      }
    },
    handleFormatError (file) {
      this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
    },
    handleProgress (event, file) { },
    handleSuccess (event, file, fileList) {
      this.$set(this.formValidate, 'receipt_js', file.response.domain + file.response.key)
    },
    handleError (event, file) {
      this.$Message.error('token已过期，请刷新页面重新上传')
    },
    handleView (img_url) {
      this.imgName = img_url
      this.visible = true
    },
    handleRemove (index) {
      this.formValidate.receipt_js = '';
    },
    doCash: function () {
      latestCashInfo({
        shop_id: this.filter.shop_id
      }).then(res => {
        if (res.code === 0) {
          this.formValidate = Object.assign({}, res.data)
          this.formValidate.shop_id = this.filter.shop_id
          this.formValidate.money_origin = 0.01
          this.showCashoutModal = true
        }
      })
    },
    /**
     * 验证手机号码格式
     */
    isPhoneIncorrect (phone) {
      var myreg = /^[1][3-9][0-9]{9}$/
      return !myreg.test(phone)
    },
    cashOutRecord () {
      let _this = this
      let routeData = _this.$router.resolve({ name: 'cash-record', params: { shop_id: _this.filter.shop_id } })
      window.open(routeData.href)
    },
    change: function (page) {
      this.loading = true
      this.filter.page = page - 1
      this.getList()
    },
    search: function () {
      this.filter.page = 0
      this.getList()
    },
    handleSubmit () {
      if (this.formValidate.receipt_js == '') {
        this.$Message.error("请上传结算函");
        return;
      }

      this.formValidate.money_origin = this.statisticsInfo.money_order_ky
      let money_origin = this.formValidate.money_origin
      this.formValidate.money_wx = (money_origin * 0.0054).toFixed(2)
      this.formValidate.money = money_origin - this.formValidate.money_wx

      // console.log(this.formValidate);return false;

      if (this.isSubmitting) return
      this.isSubmitting = true

      addCash(this.formValidate).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.showCashoutModal = false
          this.getStatistics()
        } else {
          this.$Message.error(res.text)
        }
        setTimeout(() => this.isSubmitting = false, 1000)
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    exportData () {
      let _this = this
      _this.filter.page = 0
      _this.filter.page_size = 500
      _this.export_list = []
      _this.export()
    },
    export () {
      let _this = this
      orderRecordList(this.filter).then(res => {
        if (res.code == 0) {
          if (res.data.length) {
            _this.export_list.push.apply(_this.export_list, res.data)
            _this.filter.page++
            setTimeout(() => {
              _this.export()
            }, 500)
          } else {
            _this.filter.page_size = 20
            const { export_json_to_excel } = require('../../excel/Export2Excel');
            const tHeader = ['客户姓名', '手机号码', '门店', '商品', '订单号', '收入(元)', '入账/支出(元)', '创建时间'];
            const filterVal = ['name', 'phone', 'shop_name', 'good_name', 'order_sn', 'money', 'moneys', 'created_time'];
            const data = _this.formatJson(filterVal, _this.export_list)
            export_json_to_excel(tHeader, data, '账单明细')
          }
        }
      })
    },
    getPermissionList (parent_name) {
      childBtnPermission({ parent_name }).then(res => {
        if (res.code === 0) {
          this.permissionList = res.data
        }
      })
    },
    getList () {
      orderRecordList(this.filter).then(res => {
        if (res.code == 0) {
          this.list = res.data
          this.loading = false
          this.pagenation.currentPage = parseInt(res.currentPage) + 1
          this.pagenation.totalPage = parseInt(res.totalPage)
          this.pagenation.perPage = parseInt(res.perPage)
        }
      })
    },
    /**
     * 平台/门店订单统计
     */
    getStatistics () {
      orderStatistics({
        shop_id: this.filter.shop_id
      }).then(res => {
        if (res.code === 0) {
          this.statisticsInfo = res.data || {
            money_order_all: 0,
            money_order_djs: 0,
            money_order_cashing: 0,
            money_order_ky: 0
          }
        }
      })
    },
    async initQn () {
      let qiniu = await getQiniu()
      this.upload_token = qiniu.token
    },
  },
  mounted () {
    this.initQn()
    this.getPermissionList('assets')
    this.getList()

    shopForSelect().then(res => {
      if (res.code === 0) {
        this.shop_list = res.data || []
      }
    })

    this.getStatistics()
  }
}
</script>
<style>
</style>
<style scoped lang="less">
.statistics {
  background: #f5f7fa;
  margin-top: 30px;
  padding: 18px;

  .item {
    width: 25%;
    box-sizing: border-box;
    border-right: 1px solid #eeeeee;
    padding: 0 20px 20px;
  }

  .item:last-child {
    border-right: none;
  }
}

.cash_out_modal {
  padding: 0 5%;

  .title {
    margin-top: 30px;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    color: #333333;
  }

  .item {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    margin: 10px 0;
    font-size: 14px;
    color: #666666;

    .item-name {
      width: 100px;
      margin-right: 20px;
      flex-shrink: 0;
    }

    .required::before {
      content: '*';
      color: red;
      font-size: 18px;
      padding-right: 5px;
    }

    .item-content {
      flex: 1;
    }
  }

  .title-img {
    font-size: 24px;
    color: #333333;
    text-align: center;
    margin-top: 30px;
    height: 50px;
    line-height: 50px;
    font-weight: bold;
  }

  .download-wrap {
    display: flex;
    justify-content: center;
    align-items: flex-end;
    margin-top: 20px;

    .download-pic {
      width: 430px;
      height: 538px;

      img {
        width: 100%;
        height: 100%;
        -o-object-fit: contain;
        object-fit: contain;
      }
    }

    .download-tip {
      margin-left: 30px;

      p {
        font-size: 16px;
        color: #666;
        line-height: 30px;
      }
    }
  }
}
</style>
